package com.changgou.item.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.feign.CategoryFeign;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.feign.SpuFeign;
import com.changgou.item.service.ItemService;
import com.changgou.pojo.Category;
import com.changgou.pojo.Sku;
import com.changgou.pojo.Spu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 老大哥在看着你
 *
 * @author ANG.YU
 * @date 2019-10-14 19:18
 */
@Service
public class ItemServiceImpl implements ItemService {
    @Autowired
    private TemplateEngine templateEngine;

    @Value("${pagepath}")
    private String pagepath;

    @Autowired
    private SpuFeign spuFeign;

    @Autowired
    private SkuFeign skuFeign;

    @Autowired
    private CategoryFeign categoryFeign;
    @Override
    public void staticPage(String id) {
        Map<String, Object> map = new HashMap<>();

        Context context = new Context();

        


        // 1商品
        Spu spu = spuFeign.findSpuById(id);
        map.put("spu", spu);

        // 2库存
        List<Sku> skuList = skuFeign.findSkuBySpuId(id);
        map.put("skuList", skuList);

        // 3商品图片集合
        String images = spu.getImages();
        String[] imageList = images.split(",");
        map.put("imageList", imageList);

        // 4商品分类 1 2 3
        /*<a href="#"  th:text="${category1.name}"></a>*/
        Category category1 = categoryFeign.findCategoryBySpuId(spu.getCategory1Id());
        map.put("category1", category1);
        map.put("category2", categoryFeign.findCategoryBySpuId(spu.getCategory2Id()));
        map.put("category3", categoryFeign.findCategoryBySpuId(spu.getCategory3Id()));

        // 5商品参数
        String specItems = spu.getSpecItems();
        map.put("specificationList", JSON.parseObject(specItems, Map.class));
        context.setVariables(map);

        Writer writer = null;
        try {
            writer = new PrintWriter(pagepath + id + ".html", "utf-8");
            templateEngine.process("item", context, writer);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
